import React, { useState, useRef } from 'react';
import { Upload, message, Modal, Button, Form, Select, Input } from 'antd';
import oss from '@/utils/oss/index';
import { PlusOutlined, LoadingOutlined, UploadOutlined } from '@ant-design/icons';
import Api from '@/api';

const { Option } = Select;
const videoFormat = [
  'mp4',
];

let aliosseEvent = {
  client: null,
  cpt: {},
};

const Index = (props) => {
  const { OfficialID } = JSON.parse(sessionStorage.getItem('USER')) || {};
  const videos = useRef(null);

  const {
    isModalVisible,
    setIsModalVisible,
    videoUrl,
    setVideoUrl,
    MediaData,
    setMediaData,
  } = props;
  const [upType, setUpType] = useState('1');
  const [fileList, setFileList] = useState([]);
  const [loading, setLoading] = useState(false);

  // 封面上传部分
  const beforeUpload = (file) => {
    const isVideo = videoFormat.includes(
      file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase(),
    );
    if (!isVideo) {
      message.error(`请选择视频文件`);
    }
    const isLtSize = file.size / 1024 / 1024 < 1000;
    if (!isLtSize) {
      message.error('上传文件最大不能超过1000M！');
    }
    return isVideo && isLtSize;
  };

  // 自定义封面上传
  // 文件组件自定义上传
  const handleCustomRequest = (options) => {
    options.client = (value) => {
      aliosseEvent = value;
    };
    oss.ali.uploader(options.file, 'video', options);
  };

  // 文件上传成功的响应
  const handleChange = (info) => {
    let newFileList = info.fileList;
    if (newFileList.length) {
      setLoading(true);
    }
    // 限制文件数量
    newFileList = newFileList.slice(-1);
    if (videos && newFileList.length) {
      const video = newFileList[0].originFileObj;
      const url = URL.createObjectURL(video);
      setVideoUrl(url);
    }

    // 文件链接
    newFileList = newFileList.map((file) => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });

    // 文件响应
    newFileList = newFileList.filter((file) => {
      if (file.response) {
        return file.response.res.status === 200;
      }
      return true;
    });

    if (info.file.status === 'done') {
      setLoading(false);
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    }
    setMediaData({});
    setFileList(newFileList);
  };

  const onRemove = () => {
    if (loading) {
      setLoading(false);
      aliosseEvent.client.abortMultipartUpload(aliosseEvent.cpt.name, aliosseEvent.cpt.uploadId);
    }
    return true;
  };

  const handleOk = () => {
    if (upType === '1') {
      if (!fileList.length) {
        message.warning('请上传视频！');
        return;
      }
      const fileName = fileList[0].name;
      const suffixName = fileName.slice(fileName.lastIndexOf('.') + 1);
      Api.User.UploadMedia({
        params: {
          officialID: OfficialID,
        },
        data: {
          Type: 3,
          Name: fileName,
          Url: `${fileList[0].url}`,
          Thumb: '',
          SuffixName: suffixName,
          Desc: '',
          Length: parseInt(videos.current.duration),
          Size: fileList[0].size,
          VideoResID: sessionStorage.getItem('VideoResID'),
        },
      }).then((res) => {
        if (res.Ret === 0) {
          setIsModalVisible(false);
          setMediaData({
            ...res.Data,
            MediaResID: res.Data.VideoResID,
          });
        }
      });
    }
  };

  const onCancel = () => {
    if (!fileList.length) {
      setFileList([]);
      setVideoUrl('');
    }
    setIsModalVisible(false);
    setLoading(false);
  };

  return (
    <div>
      <Modal
        title="请插入视频"
        okText="确认上传"
        visible={isModalVisible}
        onOk={() => handleOk()}
        onCancel={onCancel}
        maskClosable={false}
        footer={[
          <Button key="0" onClick={onCancel}>
            取消
          </Button>,
          <Button key="1" type="primary" loading={loading} onClick={handleOk}>
            确认上传
          </Button>,
        ]}
      >
        {/* <Form labelCol={{ span: 4, offset: 2 }}>
          <Form.Item label="上传方式" name="UpType" rules={[{ required: true }]}>
            <Select defaultValue="1" style={{ width: 200 }} onChange={(value) => setUpType(value)}>
              <Option value="1">本地上传</Option>
              <Option value="2">外部链接地址</Option>
            </Select>
          </Form.Item>
        </Form> */}
        <Form labelCol={{ span: 4, offset: 2 }}>
          <Form.Item
            label={upType === '1' ? '本地上传' : '视频地址'}
            name={upType === '1' ? 'type' : 'urltype'}
            rules={[{ required: true }]}
          >
            {upType === '1' ? (
              <Upload
                name="file"
                fileList={fileList}
                accept=".mp4"
                beforeUpload={beforeUpload}
                customRequest={handleCustomRequest}
                onChange={handleChange}
                onRemove={onRemove}
              >
                <Button>
                  <UploadOutlined />
                  上传视频
                </Button>
              </Upload>
            ) : (
              <Input
                onChange={(e) => setVideoUrl(e.target.value)}
                placeholder="请输入外部视频链接地址"
              />
            )}
          </Form.Item>
        </Form>
      </Modal>
      <div style={{ display: 'none' }}>
        <video ref={videos} src={videoUrl} controls="controls"></video>
      </div>
    </div>
  );
};

export default Index;
